package com.example.module_hp_white_noise.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.ColorInt;
import androidx.core.graphics.ColorUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Random;
import java.util.TimeZone;

public class BaseUtils {
    public static int dip2px(Context context, double dpValue) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * density + 0.5);
    }
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    /**
     * Android 6.0 以上设置状态栏颜色
     */
    public static void setStatusBar(Activity activity, @ColorInt int color) {
        // 设置状态栏底色颜色
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        activity.getWindow().setStatusBarColor(color);
        //Log.e("颜色", String.valueOf(isLightColor(color)));
        // 如果亮色，设置状态栏文字为黑色
        if (isLightColor(color)) {
            activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        }

    }

    /**
     * 判断颜色是不是亮色
     *
     * @param color
     * @return
     * @from https://stackoverflow.com/questions/24260853/check-if-color-is-dark-or-light-in-android
     */
    private static boolean isLightColor(@ColorInt int color) {
        return ColorUtils.calculateLuminance(color) >= 0.5;
    }


    /**
     * 获取StatusBar颜色，默认白色
     *
     * @return
     */
    protected @ColorInt
    int getStatusBarColor() {
        return Color.WHITE;
    }
    //设置状态栏透明、沉浸式
    public static void setStatusBarLucency(Activity activity) {
        activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        int option = activity.getWindow().getDecorView().getSystemUiVisibility() |
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
        activity.getWindow().getDecorView().setSystemUiVisibility(option);
        activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
    }
    //获取屏幕宽度
    public static int getScreenWidth(Context context){
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
//        int width = dm.widthPixels;         // 屏幕宽度（像素）
//        int height = dm.heightPixels;       // 屏幕高度（像素）
//        float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
//        int densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）
//        // 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
//        int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
//        int screenHeight = (int) (height / density);// 屏幕高度(dp)
        return dm.widthPixels;
    }
    //补零
    public static String returnValue(int v){
        String val;
        if (v < 10){
            val = String.valueOf("0"+v);
        }else {
            val = String.valueOf(v);
        }
        return val;
    }
    //毫秒转日期
    public static String formatTime(int timeMillis,String dateFormat) {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        //设置为东八区
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));

        Date date = new Date((long) timeMillis *1000);
        return simpleDateFormat.format(date);
    }
    //日期转毫秒
    public static Long formatMillisecond(String serverTime, String format) {
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINESE);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        long millisecond = 0;
        try {
            millisecond = Objects.requireNonNull(sdf.parse(serverTime)).getTime();
        } catch (Exception ignored) {
        }
        return millisecond;
    }
    //2个日期之间间隔天数
    public static int getDateDays (String startDate,String endDate) {
        int betweenTime = 0;
        @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        try {
            Date date = sdf.parse(endDate);// 通过日期格式的parse()方法将字符串转换成日期
            Date dateBegin = sdf.parse(startDate);
            long time = date.getTime() - dateBegin.getTime();
            betweenTime = (int) (time / 1000 / 60 / 60 / 24);
        } catch(Exception ignored) { }
        return betweenTime+1;
    }
    //根据时间戳获取当月最后一天时间的时间搓
    public static long secondFormatLastSecond(int timeMillis){
        Date date = new Date((long) timeMillis *1000);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        Date firstDate = cal.getTime();
        return firstDate.getTime();
    }
    //从[minVal, topVal]范围中选出cnt个不重复的数据
    public static List<Integer> genUniqueRandomVal(int minVal, int topVal, int cnt){
        int index;
        List<Integer> mBaseList = null;
        int size = topVal-minVal+1;
        if (minVal >= topVal){
            return null;
        }

        if (cnt>size){
            return null;
        }

        if (null == mBaseList){
            mBaseList = new ArrayList<Integer>();
        }

        //初始化基本数据集合
        mBaseList.clear();
        for (int i = minVal; i <= topVal; i++){
            mBaseList.add(i);
        }
        List<Integer> uniqueValList = new ArrayList<Integer>();//无重复的数据集合
        Random random = new Random();
        while (cnt > 0) {
            index = random.nextInt(size);//范围[0, size)
            uniqueValList.add(mBaseList.get(index));//添加到数据集合
            mBaseList.remove(index);//基本数据集合移除已经加到uniqueValList的数据，这样子就不会重复
            cnt--;
            size--;
        }
        return uniqueValList;
    }
    //防止反复弹出
    private static long lastClickTime;
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if ( 0 < timeD && timeD < 1000) {
            return true;
        }
        lastClickTime = time;
        return false;
    }
    /**
     * 生成随机汉字
     * @return
     */
    public static String getRandomChar(){
        String str = "";
        int hightPos;
        int lowPos;

        Random random = new Random();

        hightPos = (176 + Math.abs(random.nextInt(39)));
        lowPos = (161 + Math.abs(random.nextInt(93)));

        byte[] b = new byte[2];
        b[0] = (Integer.valueOf(hightPos)).byteValue();
        b[1] = (Integer.valueOf(lowPos)).byteValue();

        try {
            str = new String(b, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }
    /*读取json数据*/
    public static String getJson(String fileName,Context context) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
            bf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
    //判断网络连接状态
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return ((NetworkInfo) mNetworkInfo).isAvailable();
            }
        }
        return false;
    }
}
